package cda;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.hessian.himp.util.statistic.util.MonIds;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class UpdateMongo {

    private static final MonIds monIds = new MonIds();
    private static final com.mongodb.client.MongoClient client = monIds.getClient();

    public static void main(String[] args) {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("24d0aef86f7e006a630972a3d8cab275","术后首次病程记录");
        hashMap.put("76a94be509973fc45a14226f4f11a844","阶段小结");
        hashMap.put("63461242c22b3084929c5c66a31c0b99","入院记录");
        hashMap.put("cfe16c6ae1208c798930323157964cd0","疑难病例讨论记录");
        hashMap.put("0236af4bbc7b0c24d53846a9dcf41960","转科记录");
        hashMap.put("3129aceac93c2ea96db3e2e22c4f9b7d","术前小结");
        hashMap.put("59b5c08d6b2dcf9fe57eba9a7ab8face","住院病案首页");
        hashMap.put("0d63815785aa33621177113545287044","死亡病历讨论记录");
        hashMap.put("88ed56e12f6ecb445525b32acc689eef","抢救记录");
        hashMap.put("bdfdf27a02ea3c1337f478d3846e06ef","出院小结");
        hashMap.put("72af2f7e35a44a3a54fe5cdf2a65b8da","住院医嘱");
        hashMap.put("8507601d7361c1e92ee8e2ac351bf10e","会诊记录");
        hashMap.put("f08f7e7b4a9876e031989da602be7701","交接班记录");
        hashMap.put("4c3744b836e248efc864996d63e622f2","出院记录");
        hashMap.put("ad7af7cedabda7231234688c98e83609","术前讨论");
        hashMap.put("6dff3f6d3ffc868486927020ee0c0ae1","死亡记录");

        MongoCollection<Document> collection = client.getDatabase("testsql0329").getCollection("cdaContent");

        // 1.更新属性字段path
        Bson regex = Filters.regex("describe", "@");

        try (MongoCursor<Document> mongoCursor = collection.find(regex).cursor()) {
            while (mongoCursor.hasNext()) {
                Document next = mongoCursor.next();
                Object id = next.get("_id");
                String describe = next.getString("describe");

                Map<String, String> resultMap = extractAttributes(describe);

                resultMap.forEach((k, v) -> {
                    Document filter = new Document("_id", id);

                    Document update = new Document("$set", new Document("attributePath.$[elem].path", v));

                    Document arrayFilters = new Document("elem.attribute", k);
                    collection.updateOne(filter, update, new UpdateOptions().arrayFilters(Arrays.asList(arrayFilters)));
                });


                System.out.println();
            }
        }

        // 2.更新“数据源标识符”不为空的字段path
//        List<String> lines = ReadFile.ReadFileForLineList("D:\\myProject\\test\\src\\main\\resources\\cda字段映射.txt");
//        Map<String, String> filedMap = lines.stream()
//                .map(line -> line.split("#@#"))
//                .filter(parts -> parts.length == 2) // 确保分割后有两个部分
//                .collect(Collectors.toMap(parts -> parts[0], parts -> parts[1]));
//
//        Bson find = Filters.eq("tree_id", "149bc86a37c324dca49f343af776f076");
//        try (MongoCursor<Document> mongoCursor = collection.find(find).cursor()) {
//            while (mongoCursor.hasNext()) {
//                Document next = mongoCursor.next();
//                Object id = next.get("_id");
//                String dataIdentifier = next.getString("dataIdentifier");
//                String describe = next.getString("describe");
//
//                List<Document> attributePath = next.getList("attributePath", Document.class);
//                if (StringUtils.isNotBlank(dataIdentifier)) {
//                    String filed = filedMap.get(describe);
//
//                    Document filter = new Document("_id", id);
//
//                    Document update = new Document("$set", new Document("attributePath.$[elem].path", filed));
//
//                    Document arrayFilters = new Document("elem.path", "");
//                    collection.updateOne(filter, update, new UpdateOptions().arrayFilters(Arrays.asList(arrayFilters)));
//                    System.out.println();
//                }
//            }
//        }




        // 查所有标识符不为空的数据
//        Bson regex = Filters.ne("dataIdentifier", "");
//        try (MongoCursor<Document> mongoCursor = collection.find(regex).cursor()) {
//            HashSet<String> hashSet = new HashSet<>();
//            while (mongoCursor.hasNext()) {
//                Document document = mongoCursor.next();
//                hashSet.add(document.getString("describe") + "#@#" + hashMap.get(document.getString("treeparentId")));
//            }
//
//            hashSet.stream().filter(str -> (!str.startsWith("其中， @")) &&
//                            (!str.startsWith("其中，@")) &&
//                            (!str.startsWith("其中， @")) &&
//                            (!str.startsWith("其中@")) &&
//                            (!str.startsWith("其中缺省值， @")) &&
//                            (!str.startsWith("其 中 缺 省 值 ，@")) &&
//                            (!str.startsWith("其中缺省值@")) &&
//                            (!str.startsWith("O其中， @")) &&
//                            (!str.startsWith("其 中 ，@")) &&
//                            (!str.startsWith("其中缺省值，@")))
//                    .forEach(System.out::println);
//        }




    }

    public static Map<String, String> extractAttributes(String text) {
        Map<String, String> map = new HashMap<>();
        // 定义正则表达式模式
//        String regex = "@(\\w+)=\"([^\"]+)\"";
        String regex = "@([\\w:]+)=\"([^\"]+)\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        // 查找匹配项
        while (matcher.find()) {
            String attribute = matcher.group(1); // xxx
            String value = matcher.group(2); // yyy
            map.put(attribute, value);
        }

        return map;
    }

}
